package controllers.admin.permission;

import controllers.Secure;
import controllers.admin.secure.Security;
import controllers.admin.secure.Security;
import controllers.deadbolt.DeadboltHandler;
import controllers.deadbolt.ExternalizedRestrictionsAccessor;
import controllers.deadbolt.RestrictedResourcesHandler;
import models.permission.User;
import models.deadbolt.ExternalizedRestrictions;
import models.deadbolt.RoleHolder;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;

public class AclDeadboltHandler extends Controller implements DeadboltHandler {
	private static final RestrictedResourcesHandler RESTRICTED_RESOURCES_HANDLER = new AclRestrictedResourcesHandler();

	public void beforeRoleCheck()
	{
	    // Note that if you provide your own implementation of Secure's Security class you would refer to that instead
	    try
	    {
	        if (!Security.isConnected())
	        {
				String url = "GET".equals(request.method) ? request.url : "/";
				flash.put("url", url);

	            if(StringUtils.contains(url,"/admin")){
					redirect("/admin/login");
				}else{
					Secure.login();
				}
	        }
	    }
	    catch (Throwable t) {
	        // handle this in an app-specific way
	    }
	}

	public RoleHolder getRoleHolder() {
		String userName = Security.connected();
		return User.findUserByUserName(userName);
	}

	public void onAccessFailure(String controllerClassName) {
		forbidden();
	}

	public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() {
		return new ExternalizedRestrictionsAccessor() {
			public ExternalizedRestrictions getExternalizedRestrictions(
					String name) {
				return null;
			}
		};
	}

	public RestrictedResourcesHandler getRestrictedResourcesHandler() {
		return RESTRICTED_RESOURCES_HANDLER;
	}
}
